package com.lefevre.cms.utils;

import com.lefevre.cms.LefevreCmsApplication;
import com.lefevre.cms.web.action.KaptchaConfig;
import org.springframework.boot.system.ApplicationHome;

import java.io.File;
import java.net.URL;


/**
 * 获取项目jar的根目录
 *
 * @author Lefevre
 */
public class PathUtil {
    //项目根目录
    private static String rootPath = "";

    //论坛外部目录
    private static String defaultExternalDirectory = "";


    public static String rootPath() {
        if ("".equals(rootPath)) {
            readPath();
        }
        return rootPath;
    }

    public static String defaultExternalDirectory() {
        if ("".equals(defaultExternalDirectory)) {
            readPath();
        }
        return defaultExternalDirectory;
    }

    private static void readPath() {
        ApplicationHome home = new ApplicationHome(LefevreCmsApplication.class);
        File jarFile = home.getSource();
        String path = jarFile.getParentFile().toString();
        //F:\JAVA\cms-pro\target\classes
        rootPath = path + File.separator + "classes";

        //论坛外部目录
        Object externalDirectory = YmlUtils.getYmlProperty("application.yml", "bbs.externalDirectory");
        //如果已设置了论坛外部目录   G:\bbs
        if (externalDirectory != null && !"".equals(externalDirectory.toString().trim())) {
            defaultExternalDirectory = externalDirectory.toString();
        } else {
            //F:\JAVA\cms-pro\target\bbs
            defaultExternalDirectory = path + File.separator + "bbs";
        }
    }

    /**
     * 自动路径 jar启动时使用外部路径 IDE启动时使用内部路径
     *
     * @return
     */
    public static String autoRootPath() {
        //jar启动
        if (isStartupFromJar()) {
            return defaultExternalDirectory();
        } else {//IDE启动
            return rootPath();
        }
    }

    /**
     * 判断是在jar中运行,还是IDE中运行
     *
     * @return true: jar启动   false: IDE启动
     */
    public static boolean isStartupFromJar() {
        URL url = KaptchaConfig.class.getResource("");
        assert url != null;
        return "jar".equals(url.getProtocol());
    }

}
